<?php

namespace App\Services;

use App\Enum\TravelEnum;
use App\Models\VillagerUserModel;
use Illuminate\Http\Request;
use App\Models\TravelAddressModel;

class TravelAddressService
{
    /**
     * 常用地址
     * @param $userId
     * @author ninetyseven.
     * @date 2023-04-03 23:35
     */
    public static function getTravelAddress(int $userId)
    {
        return TravelAddressModel::query()->where(['user_id' => $userId])->orderByDesc('id')->limit(6)->get()->toArray();
    }

    /**
     * 添加地址
     * @param $request
     * @author ninetyseven.
     * @date 2023-04-03 23:35
     */
    public static function addTravelAddress(Request $request)
    {
        if (empty($request->address)) {
            throw new \Exception('地址不能为空：address');
        }
        if (empty($request->location)) {
            throw new \Exception('地址位置不能为空：location');
        }
        if (empty($request->short_address)) {
            throw new \Exception('详细地址不能为空：location');
        }

        if($request->id){
            $data = [
                'address' => $request->address,
                'short_address' => $request->short_address,
                'location' => $request->location,
                'remark' => $request->remark,
                'updated_at' => time(),
            ];
            $result = TravelAddressModel::query()->where('id', $request->id)->update($data);
        }else{
            if(request()->appId == TravelEnum::PLATFORM_VILLAGER){
                //村民最多添加2个地址
                $count = TravelAddressModel::query()->where(['user_id' => $request->userId,'platform_id' => request()->appId])->count();
                if($count >= 2){
                    throw new \Exception('最多添加2个地址');
                }
                $data = [
                    'user_id' => $request->userId,
                    'platform_id' => $request->appId,
                    'address' => $request->address,
                    'short_address' => $request->short_address,
                    'location' => $request->location,
                    'status' => 0,
                    'remark' => $request->remark,
                    'created_at' => time(),
                    'updated_at' => time(),
                ];
                $result = TravelAddressModel::create($data);
            }else{
                $data = [
                    'user_id' => $request->userId,
                    'platform_id' => $request->appId,
                    'address' => $request->address,
                    'short_address' => $request->short_address,
                    'location' => $request->location,
                    'status' => 0,
                    'remark' => $request->remark,
                    'created_at' => time(),
                    'updated_at' => time(),
                ];
                $result = TravelAddressModel::create($data);
            }
        }
        return $result;
    }
}
